<?php

// phpMyRealty 3
//
// File Name: search.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

$page = 'search';

include ( './config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// LISTINGS SEARCH SECTION

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $lang['Property_Search'];

if ( ( (isset($_POST['type']) && $_POST['type'] != '' && $_POST['type'] != 'ANY' && !eregi('^[0-9]+$', $_POST['type'])) || (isset($_GET['type']) && $_GET['type'] != '' && $_GET['type'] != 'ANY' && !eregi('^[0-9]+$', $_GET['type'])) ) ) {
 die ();
} 

if (isset($_POST['type'])  && $_POST['type'] != 'ANY')
 $title .= ' - ' . getnamebyid(TYPES_TABLE, $_POST['type']);

if (isset($_GET['type']) && $_GET['type'] != 'ANY')
 $title .= ' - ' . getnamebyid(TYPES_TABLE, $_GET['type']);

$initiate_maps = 'ON';

$initAjax = TRUE;

include ( PATH . '/includes/ajaxFavorites.php');

// Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

// Define an array of all the search elements
$search = array();

// If this is the first time we call this script
// we use the _POST'ed variable, if not, we use
// _GET method
if (!isset($_GET['page']) && isset($_GET['type']))
 {
  $_GET['page'] = 0;
 }

if (isset($_POST['locationX']))
 {
  $z = 1;
  for ($x = 0; $x < count ( $_POST['locationX'] ); $x++)
   {
    if ($_POST['locationX'][$x] != "") 
     {
      $locs[$z] = $_POST['locationX'][$x];
      $z++;
     }
   }

  $_POST['locationX'] = implode(":", $locs);
 }

// If we pressed the search button we need to 
// convert some complex variables like Features
// which look like 1:2:3:4 into the simple
// arrays for the future use
if (isset($_POST['property_search']))
 {
  if (isset($_POST['buildings']) && is_array($_POST['buildings']) )
   $_POST['buildings'] = implode (':', $_POST['buildings']);

  if (isset($_POST['appliances']) && is_array($_POST['appliances']) )
   $_POST['appliances'] = implode (':', $_POST['appliances']);

  if (isset($_POST['features']) && is_array($_POST['features']) )
   $_POST['features'] = implode (':', $_POST['features']);

  $search = array_map ('safehtml', $_POST);
 }
else
{
  // If the search button was not pressed we use
  // GET method, urldecode variables and remove html tags
  // which can be harmful for the script
  $search = array_map ('rawurldecode', $_GET);
  $search = array_map ('safehtml', $search);
}

 if (isset($search['price_min_any'])) {
     $search['price_min'] = $search['price_min_any'];
 }
 if (isset($search['price_max_any'])) {
     $search['price_max'] = $search['price_max_any'];
 }
 $price_type = '';
 if ($search['type2'] != 'ANY') {
     $sql = 'SELECT class FROM '.TYPES2_TABLE.' WHERE id = "'.$search['type2'].'"';
     $r = $db->query($sql);
     $f = $db->fetcharray($r);
     $db->freeresult($r);
     $price_type = $f['class'];
     if (isset($search['price_min_'.$price_type])) {
         $search['price_min'] = $search['price_min_'.$price_type];
     }
     if (isset($search['price_max_'.$price_type])) {
         $search['price_max'] = $search['price_max_'.$price_type];
     }
 }
 $sql = 'SELECT DISTINCT class FROM '.TYPES2_TABLE;
 $r = $db->query($sql);
 while ($f = $db->fetcharray($r)) {
     unset($search['price_min_'.$f['class']]);
     unset($search['price_max_'.$f['class']]);
 }
 $db->freeresult($r);
 unset($search['price_min_any']);
 unset($search['price_max_any']);
 // SEARCH CACHE remembers the last listings search
// initiated by user

// Generate GET vars and push it into the session variable
// to be able to return to this search page later
$session->varunset('listingsearchvariables');
$searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode(unsafehtml($value)) . '&amp;';
$session->set('listingsearchvariables', $searchURL);

// Pagination
if (isset($_GET['page'])) $page = $search['page']; else $page = 0;
 unset($search['page']);
$results_page = $page * $conf['search_results'];

$session->varunset('listingsearchvariablespage');
$searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode(unsafehtml($value)) . '&amp;';
$session->set('listingsearchvariablespage', $searchURL);

// Errors output if needed

// Initially we think that no errors were found
$count_error = 0;

/*

// If keyword was not specified we stop processing
if (isset($search['description']) && empty($search['description']))
{ echo $lang['Field_Empty'] . ' <strong><span class="warning">' . $lang['Search_Keyword'] . '</span></strong><br />'; $count_error++; }
//

*/

// If there were errors found we print the 
// errors descriptions
if ($count_error != 0)
 {
  echo table_header ( $lang['Information'] );
  echo $lang['Errors_Found'] . ': ' . $count_error;
  echo table_footer ();
 }

// Output the results
//
// If no errors found we output the results
if ($count_error == 0)
 {

// Find all the zip codes within specified range
if (isset($search['your_zip']) && isset($search['miles']))
 {
   $found_zip_codes = get_zips_in_range ($search['your_zip'], $search['miles']);

   // If some zips were found we create an IN query.
   if (count($found_zip_codes) > 0)
    {

     $sql_zip_codes = 'IN (';

     foreach($found_zip_codes as $zips => $dists)
      $sql_zip_codes.= '"' . $zips . '", ';

     $sql_zip_codes.= '"00000")';

    }

   // Or put an unreal zip code not to show results at all
   else $sql_zip_codes = ' = "ZZZZZ"';
 }

  // Generate the SQL query

  // Title/descr language to use (if available)
  $title = str_replace( 'name', 'title', $language_in );
  $description = str_replace( 'name', 'description', $language_in );

  $sql = 'SELECT ' . $title . ', ' . $description . ', ' . PROPERTIES_TABLE . '.* FROM ' . PROPERTIES_TABLE . ' WHERE ';

  $sql.= 'approved = 1 ';

  if (isset($search['userid']) && !empty($search['userid'])) 
   $sql.= ' AND userid = "' . $search['userid'] . '" ';

  if (isset($search['id']) && !empty($search['id'])) 
   $sql.= ' AND id = "' . $search['id'] . '" ';

  if (isset($search['mls']) && !empty($search['mls'])) 
   $sql.= ' AND (mls = "' . $search['mls'] . '" OR id = "' . $search['mls'] . '")';

  if (isset($search['title']) && !empty($search['title'])) 
   $sql.= ' AND title LIKE "%' . $search['title'] . '%" ';

  if (isset($search['type']) && $search['type'] != 'ANY') 
   $sql.= ' AND type = "' . $search['type'] . '" ';

  if (isset($search['type2']) && $search['type2'] != 'ANY') 
   $sql.= ' AND type2 = "' . $search['type2'] . '" ';

  if (isset($search['style']) && $search['style'] != 'ANY') 
   $sql.= ' AND style = "' . $search['style'] . '" ';

  if (isset($search['status']) && $search['status'] != 'ANY') 
   $sql.= ' AND status = "' . $search['status'] . '" ';

  // Multiple keyword search
  if (isset($search['keyword']) && !empty($search['keyword'])) {
   $inkey = explode (",", $search['keyword']);

  $sql.= ' AND ( description = "0" ';

  foreach($inkey as $key => $value) {

   $sql.= ' OR mls = "' . trim($value) . '" OR id = "' . trim($value) . '" '; 
   $sql.= ' OR description LIKE "%' . trim($value) . '%" OR title LIKE "%' . trim($value) . '%" '; 
   $sql.= ' OR zip = "' . trim($value) . '" '; 

   $r00 = $db->query('SELECT id FROM ' . TYPES_TABLE . ' WHERE name = "' . trim($value) . '"');
  
   if ($db->numrows($r00) > 0) {
    $f00 = $db->fetcharray($r00);
    $sql.= ' OR type = "' . $f00['id'] . '" ';
   }

   $r01 = $db->query('SELECT selector FROM ' . LOCATION1_TABLE . ' WHERE category = "' . trim($value) . '"');
  
   if ($db->numrows($r01) > 0) {
    $f01 = $db->fetcharray($r01);
    $sql.= ' OR location2 LIKE "' . $f01['selector'] . '#%#%" ';
   }

   $r02 = $db->query('SELECT catsubsel FROM ' . LOCATION2_TABLE . ' WHERE subcategory = "' . trim($value) . '"');
   
   if ($db->numrows($r02) > 0) {
    $f02 = $db->fetcharray($r02);
    $sql.= ' OR location2 LIKE "%#' . $f02['catsubsel'] . '#%" ';
   }

   $r03 = $db->query('SELECT catsubsubsel FROM ' . LOCATION3_TABLE . ' WHERE subsubcategory = "' . trim($value) . '"');
   
   if ($db->numrows($r03) > 0) {
    $f03 = $db->fetcharray($r03);
    $sql.= ' OR location2 LIKE "%#%#' . $f03['catsubsubsel'] . '" ';
   }
   }
   $sql.= ' ) ';
  }

  if (isset($search['description']) && !empty($search['description'])) 
   $sql.= ' AND description LIKE "%' . $search['description'] . '%" ';

  if (isset($search['size']) && !empty($search['size'])) 
   $sql.= ' AND size LIKE "%' . $search['size'] . '%" ';

  if (isset($search['dimensions']) && !empty($search['dimensions'])) 
   $sql.= ' AND dimensions = "' . $search['dimensions'] . '" ';

  if (isset($search['bathrooms']) && !empty($search['bathrooms'])) 
   $sql.= ' AND bathrooms >= "' . $search['bathrooms'] . '" ';

  if (isset($search['half_bathrooms']) && !empty($search['half_bathrooms'])) 
   $sql.= ' AND half_bathrooms >= "' . $search['half_bathrooms'] . '" ';

  if (isset($search['bedrooms']) && !empty($search['bedrooms'])) 
   $sql.= ' AND bedrooms >= "' . $search['bedrooms'] . '" ';

  //3 level locations

  if (!isset($search['location1']) || $search['location1'] == 'ANY') { 
   $search['location1'] = '%'; 
   $search['location2'] = '%'; 
   $search['location3'] = '%'; 
  }

  if (!isset($search['location2']) || $search['location2'] == 'ANY') {
   $search['location2'] = '%';
   $search['location3'] = '%';
  }

  if (!isset($search['location3']) || $search['location3'] == 'ANY')
   $search['location3'] = '%';

  if ($search['location1'] != '%' && !eregi('^[0-9]+$', $search['location1'] && $search['location1'] != 'ANY')) die('Unknown input');
  if ($search['location2'] != '%' && !eregi('^[0-9]+$', $search['location2'] && $search['location2'] != 'ANY')) die('Unknown input');
  if ($search['location3'] != '%' && !eregi('^[0-9]+$', $search['location3'] && $search['location3'] != 'ANY')) die('Unknown input');

  $locationsearch = $search['location1'] . '#' . $search['location2'] . '#' . $search['location3'];

  if (isset($search['location1']))
   $sql.= ' AND location2 LIKE "' . $locationsearch . '" ';

  //

  if (isset($search['your_zip']) && isset($search['miles']) && $search['your_zip'] != '' && $search['miles'] != '' && count($found_zip_codes) > 0)
   $sql.= ' AND zip ' . $sql_zip_codes;

  if (isset($search['your_zip']) && isset($search['miles']) && $search['your_zip'] != '' && $search['miles'] != '' && count($found_zip_codes) == 0)
   $sql.= ' AND zip ' . $sql_zip_codes;

  if (isset($search['zip']) && !empty($search['zip']))
   $sql.= ' AND zip = "' . $search['zip'] . '" ';

  if (isset($search['address']) && !empty($search['address'])) 
   {
    $sql.= 'AND (address1 LIKE "%' . $search['address'] . '%" ';
    $sql.= ' OR address2 LIKE "%' . $search['address'] . '%" ) ';
   }

  if (isset($search['price_max']) && $search['price_max'] == 'ANY') $search['price_max'] = '';
  if (isset($search['price_min']) && $search['price_min'] == 'ANY') $search['price_min'] = '';

  if (isset($search['price_max']) && isset($search['price_min']) )
   {
    if ($search['price_max'] != '' && $search['price_min'] == '' && eregi('^[0-9]+$', $search['price_max'])) 
     $sql.= ' AND price <= "' . $search['price_max'] . '" ';

    if ($search['price_max'] == '' && $search['price_min'] != '' && eregi('^[0-9]+$', $search['price_min'])) 
     $sql.= ' AND price >= "' . $search['price_min'] . '" ';

    if ($search['price_max'] != '' && $search['price_min'] != '' && eregi('^[0-9]+$', $search['price_min']) && eregi('^[0-9]+$', $search['price_max'])) 
     $sql.= ' AND price >= "' . $search['price_min'] . '" AND price <= "' . $search['price_max'] . '" ';
   }

  if (isset($search['directions']) && !empty($search['directions'])) 
   $sql.= ' AND directions LIKE "%' . $search['directions'] . '%" ';

  if (isset($search['year_built']) && !empty($search['year_built'])) 
   $sql.= ' AND year_built = "' . $search['year_built'] . '" ';

	// Custom fields
   $custom_fields = array(
   					'custom1' => $search['custom1'],
   					'custom2' => $search['custom2'],
   					'custom3' => $search['custom3'],
   					'custom4' => $search['custom4'],
   					'custom5' => $search['custom5'],
   					'custom6' => $search['custom6'],
   					'custom7' => $search['custom7'],
   					'custom8' => $search['custom8'],
   					'custom9' => $search['custom9'],
   					'custom10' => $search['custom10'],
   );
   foreach ( $custom_fields AS $key => $value )
   {
   		if ( $value != '' && isset( $value ) )
   		{
   			// Check if this is an input field
   			$check_fields = "SELECT id, type FROM " . FIELDS_TABLE . " WHERE field = '" . $key . "' ";
   			$r = $db->query( $check_fields ) or error( 'Critical Error', mysql_error() );
   			$f = $db->fetcharray( $r );
   			if ( $f['type'] == 'input' )
   			{      				
   				// Make sure we search for {INPUT}value rather than just value
   				$value = '{INPUT}' . $value;
   			}
   			$sql .= ' AND ' . $key . ' = "' . $value . '" ';
   		}
   }

  // Additional Out Buildings

  if (isset($search['buildings']) && !empty($search['buildings'])) 
   {

    if (strstr($search['buildings'], ':'))
     {

      $search_buildings2 = explode (':', $search['buildings']);
      foreach($search_buildings2 as $search_buildings)
       {
 	$sql.= ' AND (buildings LIKE "%:' . $search_buildings . ':%" 
        OR buildings LIKE "%:' . $search_buildings . '"  
	OR buildings LIKE "' . $search_buildings . ':%" 
	OR buildings LIKE "' . $search_buildings . '" ) ';
       }
     }

    else

     $sql.= ' AND (buildings LIKE "%:' . $search['buildings'] . ':%" 
     OR buildings LIKE "%:' . $search['buildings'] . '"  
     OR buildings LIKE "' . $search['buildings'] . ':%" 
     OR buildings LIKE "' . $search['buildings'] . '" ) ';
   }

  // Appliances Included
  if (isset($search['appliances']) && !empty($search['appliances'])) 
   {

    if (strstr($search['appliances'], ':'))
     {

      $search_appliances2 = explode (':', $search['appliances']);
      foreach($search_appliances2 as $search_appliances)
       {
	$sql.= ' AND (appliances LIKE "%:' . $search_appliances . ':%" 
	 OR appliances LIKE "%:' . $search_appliances . '"  
	 OR appliances LIKE "' . $search_appliances . ':%" 
	 OR appliances LIKE "' . $search_appliances . '" ) ';
       }
     }

    else
     {
      $sql.= ' AND (appliances LIKE "%:' . $search['appliances'] . ':%" 
       OR appliances LIKE "%:' . $search['appliances'] . '"  
       OR appliances LIKE "' . $search['appliances'] . ':%" 
       OR appliances LIKE "' . $search['appliances'] . '" ) ';
     }
   }

  // Features
  if (isset($search['features']) && !empty($search['features'])) 
   {

    if (strstr($search['features'], ':'))
     {

      $search_features2 = explode (':', $search['features']);
      foreach($search_features2 as $search_features)
       {
 	$sql.= ' AND (features LIKE "%:' . $search_features . ':%" 
	 OR features LIKE "%:' . $search_features . '"  
	 OR features LIKE "' . $search_features . ':%" 
	 OR features LIKE "' . $search_features . '" ) ';
       }
     }

    else

     $sql.= ' AND (features LIKE "%:' . $search['features'] . ':%" 
     OR features LIKE "%:' . $search['features'] . '"  
     OR features LIKE "' . $search['features'] . ':%" 
     OR features LIKE "' . $search['features'] . '" ) ';
   }   

  if (isset($search['garage']) && $search['garage'] != 'ANY') 
   $sql.= ' AND garage = "' . $search['garage'] . '" ';

  if (isset($search['garage_cars']) && !empty($search['garage_cars'])) 
   $sql.= ' AND garage_cars = "' . $search['garage_cars'] . '" ';

  if (isset($search['basement']) && $search['basement'] != 'ANY') 
   $sql.= ' AND basement = "' . $search['basement'] . '" ';

  if (isset($search['image_uploaded'])) 
   $sql.= ' AND image_uploaded = "' . $search['image_uploaded'] . '" ';
  // Add ORDER BY and LIMIT functions into the SQL
  $sql2 = $sql;

  // Make all featured listings come first
  $sql2.= ' ORDER BY ';

  if (!isset($search['seed']))
   $search['seed'] = 0;

  if (isset($search['order_by']) && $search['order_by'] != 'ANY' &&
     ($search['order_by'] == 'price' ||
     $search['order_by'] == 'date_added' || $search['order_by'] == 'bedrooms' ||
     $search['order_by'] == 'bathrooms')) 
   $sql2.= ' ' . $search['order_by'] . ' ';
  else
   $sql2.= ' featured, RAND(' . $search['seed'] . ') ';

  if (isset($search['order_by']) && $search['order_by'] != 'ANY' 
  && isset($search['order_by_type']) && $search['order_by_type'] != 'ANY' &&
  ($search['order_by_type'] == 'DESC' || $search['order_by_type'] == 'ASC' )) 
   $sql2.= $search['order_by_type'];

  $sql2.=  ' LIMIT ' . $results_page . ', ' . $conf['search_results'];
  
  // End creating sql query

  // If property type specified we add it into the table
  // header

  if (isset($search['type']) && $search['type'] != 'ANY') {
   // Select all property types from the database
   $sql5 = 'SELECT id, ' . $language_in . ', counter FROM ' . TYPES_TABLE . ' WHERE id = ' . $search['type'];
   $r5 = $db->query ( $sql5 ) or error ('Critical Error', mysql_error () );
   $f5 = $db->fetcharray( $r5 );
   $table_category = ' / ' . $f5[1];
  }
  else 
   $table_category = '';

  echo ' <br /><div align="left">' . $lang['Order_By'] . ': <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariablespage') . '&amp;page=0&amp;order_by=date_added&order_by_type=DESC">' . $lang['Date_Added'] . '</a> | ';  
  echo ' <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariablespage') . '&amp;page=0&amp;order_by=bedrooms&order_by_type=ASC">' . $lang['Listing_Bedrooms'] . '</a> | ';  
  echo ' <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariablespage') . '&amp;page=0&amp;order_by=bathrooms&order_by_type=ASC">' . $lang['Listing_Bathrooms'] . '</a> | ';  
  echo ' <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariablespage') . '&amp;page=0&amp;order_by=price&order_by_type=ASC">' . $lang['Listing_Price'] . ' (ASC)</a> | ';  
  echo ' <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariablespage') . '&amp;page=0&amp;order_by=price&order_by_type=DESC">' . $lang['Listing_Price'] . ' (DESC)</a><br /><br /></div> ';  

  echo table_header ( $lang['Property_Search'] . $table_category);

  echo '
   <table width="100%" cellpadding="5" cellspacing="0" border="0">
       ';

  // Fetch number of all possible results
  $r = $db->query($sql) or error ('Critical Error', mysql_error ());
  
  // Fetch number of results per page (using LIMIT)
  $r2 = $db->query($sql2) or error ('Critical Error', mysql_error ());

  // Print 'Nothing was found' if number of found listings is 0
  if ($db->numrows($r) == 0)
   echo '<tr><td align="center"><span class="warning">' . $lang['Nothing_Found'] . '</span></td></tr>';

  $i = 0;

  if ($db->numrows($r) != 0)
   echo '<form action = "' . URL . '/comparelistings.php" method = "POST">';

  $tpl = implode ('', file( PATH . '/templates/' . $cookie_template . '/tpl/property_search_short.tpl' ));

  while ($f = $db->fetcharray( $r2 ))
   {

    $f = array_map ( 'if_empty', $f);

    // Starting a new template
    $template = new Template;
    
    // Load user short search results template
    $template->load ( $tpl );


    $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE id = ' . $f['userid'] . ' LIMIT 1';
    $r_user = $db->query ( $sql );
    $f_user = $db->fetcharray ( $r_user );

    if ($f_user['package'] != '0' && $f_user['package'] != '')
     {
  
      $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE  . ' WHERE id = ' . $f_user['package'] . ' LIMIT 1';
      $r_package = $db->query ( $sql );
      $f_package = $db->fetcharray ( $r_package );

     }

    else
 
     {
    
      $f_package['listings'] = $conf['free_listings'];
      $f_package['gallery'] = $conf['free_gallery'];
      $f_package['mainimage'] = $conf['free_mainimage'];
      $f_package['photo'] = $conf['free_photo'];
      $f_package['phone'] = $conf['free_phone'];
      $f_package['address'] = $conf['free_address'];

     }

    // VALUES

    // Replace the template variables
    
	// Default
	if (trim($f[0]) != '')
		$f['title'] = trim($f[0]);
		
	if (trim($f[1]) != '')
		$f['description'] = trim($f[1]);

    if (favoriteListingsCheck($f['id'])) {
     $template->set ( 'favorites', '<div id="favorites-' . $f['id'] . '" name="favorites-' . $f['id'] . '" style="display: inline"><span style="cursor: pointer; display: block;" class="favorites" onclick="javascript:xajax_favorites_remove(\'' . $f['id'] . '\');">' . $lang['Favorites_Remove'] . '</span></div>');
    } else {
     $template->set ( 'favorites', '<div id="favorites-' . $f['id'] . '" name="favorites-' . $f['id'] . '" style="display: inline"><span style="cursor: pointer; display: block;" class="favorites" onclick="javascript:xajax_favorites(\'' . $f['id'] . '\');">' . $lang['Favorites_Add'] . '</span></div>');
    }

    if ($conf['rewrite'] == 'ON')
     $template->set ( 'link', URL . '/Listing/' . rewrite ( getnamebyid ( TYPES_TABLE, $f['type'] ) ) . '/' . $f['id'] . '_' . rewrite($f['title']) . '.html'  );
    else
     $template->set ( 'link', URL . '/viewlisting.php?id=' . $f['id']);

    if ($f_package['mainimage'] == 'ON')
     $template->set ( 'image', show_image ('images', $f['id']) );
    else
     $template->set ( 'image', '' );

    $template->set ( 'mls', $f['mls'] );
    $template->set ( 'title', $f['title'] );
    $template->set ( 'type', getnamebyid ( TYPES_TABLE, $f['type'] ) );
    $template->set ( 'type2', getnamebyid ( TYPES2_TABLE, $f['type2'] ) );
    $template->set ( 'style', getnamebyid ( STYLES_TABLE, $f['style'] ) );

    $description = substr(removehtml(unsafehtml($f['description'])), 0, $conf['search_description']);
    $description = substr($description, 0, strrpos($description, ' ')) . ' ... ';
    $template->set ( 'description', $description );
    unset ($description);
    
    $template->set ( 'lot_size', $f['size'] );
    $template->set ( 'dimensions', $f['dimensions'] );

    if ($f['bathrooms'] < 1)
     $template->set ( 'bathrooms', '-' );
    else
     $template->set ( 'bathrooms', $f['bathrooms'] );

    $template->set ( 'half_bathrooms', $f['half_bathrooms'] );

    if ($f['bedrooms'] < 1)
     $template->set ( 'bedrooms', '-' );
    else
     $template->set ( 'bedrooms', $f['bedrooms'] );

    if ($f['garage_cars'] < 1)
     $template->set ( 'garage_cars', '-' );
    else
     $template->set ( 'garage_cars', $f['garage_cars'] );

    $cat = explode ("#", $f['location2']);
    $r11 = $db->query('SELECT category FROM ' . LOCATION1_TABLE . ' WHERE selector = "' . $cat[0] . '"');
    $f11 = $db->fetcharray($r11);
    $template->set ( 'location1', $f11['category'] );

    $r22 = $db->query('SELECT subcategory FROM ' . LOCATION2_TABLE . ' WHERE catsubsel = "' . $cat[1] . '"');
    $f22 = $db->fetcharray($r22);
    $template->set ( 'location2', $f22['subcategory'] );

    $r33 = $db->query('SELECT subsubcategory FROM ' . LOCATION3_TABLE . ' WHERE catsubsubsel = "' . $cat[2] . '"');
    $f33 = $db->fetcharray($r33);
    $template->set ( 'location3', $f33['subsubcategory'] );
    
    if ($f['display_address'] == 'YES' && $f_package['address'] == 'ON')
     {
      $template->set ( 'address1', $f['address1'] );
      $template->set ( 'address2', $f['address2'] );
      $template->set ( 'zip', $f['zip'] );
     }
    elseif ($f['display_address'] != 'YES' || $f_package['address'] != 'ON')
     {
      $template->set ( 'address1', ' ' );
      $template->set ( 'address2', ' ' );
      $template->set ( 'zip', ' ' );
     }

    $template->set ( 'price', pmr_number_format($f['price']) );
    $template->set ( 'currency', $conf['currency'] );
    $template->set ( 'directions', $f['directions'] );
    $template->set ( 'year_built', $f['year_built'] );
    $template->set ( 'buildings', show_multiple ( BUILDINGS_TABLE, $f['buildings'] ) );
    $template->set ( 'appliances', show_multiple ( APPLIANCES_TABLE, $f['appliances'] ) );
    $template->set ( 'features', show_multiple ( FEATURES_TABLE, $f['features'] ) );
    $template->set ( 'garage', getnamebyid ( GARAGE_TABLE, $f['garage'] ) );
    $template->set ( 'basement', getnamebyid ( BASEMENT_TABLE, $f['basement'] ) );
    
    $template->set ( 'date_added', printdate($f['date_added']) );
    $template->set ( 'date_updated', printdate($f['date_updated']) );
    $template->set ( 'date_upgraded', printdate($f['date_upgraded']) );
    
    $template->set ( 'ip_added', $f['ip_added'] );
    $template->set ( 'ip_updated', $f['ip_updated'] );
    $template->set ( 'ip_upgraded', $f['ip_upgraded'] );
    
    $template->set ( 'new', newitem ( PROPERTIES_TABLE, $f['id'], $conf['new_days']) );
    $template->set ( 'updated', updateditem ( PROPERTIES_TABLE, $f['id'], $conf['updated_days']) );
    $template->set ( 'featured', featureditem ( $f['featured'] ) );
    
    $template->set ( 'hits', $f['hits'] );

    $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE approved = 1 AND id = ' . $f['userid'] . ' LIMIT 1';
    $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
    $f_user = $db->fetcharray ($r_user);

    $template->set ( 'view_realtor', '<a href="' . URL . '/viewuser.php?id=' . $f['userid'] . '">' . $f_user['first_name'] . ' ' . $f_user['last_name'] . '</a>');

    $template->set ( 'checkbox', '<input type="checkbox" name="compare[]" value="' . $f['id'] . '">');
    
    // Names
    
    $template->set ( '@mls', $lang['Listing_MLS'] );
    $template->set ( '@title', $lang['Listing_Title'] );
    $template->set ( '@type', $lang['Listing_Property_Type'] );
    $template->set ( '@style', $lang['Listing_Style'] );
    $template->set ( '@description', $lang['Listing_Description'] );
    $template->set ( '@lot_size', $lang['Listing_Lot_Size'] );
    $template->set ( '@dimensions', $lang['Listing_Dimensions'] );
    $template->set ( '@bathrooms', $lang['Listing_Bathrooms'] );
    $template->set ( '@half_bathrooms', $lang['Listing_Half_Bathrooms'] );
    $template->set ( '@bedrooms', $lang['Listing_Bedrooms'] );
    $template->set ( '@location', $lang['Search_Location'] );
    $template->set ( '@city', $lang['City'] );
    $template->set ( '@address1', $lang['Listing_Address1'] );
    $template->set ( '@address2', $lang['Listing_Address2'] );
    $template->set ( '@zip', $lang['Zip_Code'] );
    $template->set ( '@price', $lang['Listing_Price'] );
    $template->set ( '@directions', $lang['Listing_Directions'] );
    $template->set ( '@year_built', $lang['Listing_Year_Built'] );
    $template->set ( '@buildings', $lang['Listing_Additional_Out_Buildings'] );
    $template->set ( '@appliances', $lang['Listing_Appliances_Included'] );
    $template->set ( '@features', $lang['Listing_Features'] );
    $template->set ( '@garage', $lang['Listing_Garage'] );
    $template->set ( '@garage_cars', $lang['Listing_Garage_Cars'] );
    $template->set ( '@basement', $lang['Listing_Basement'] );
    
    $template->set ( '@date_added', $lang['Date_Added'] );
    $template->set ( '@date_updated', $lang['Date_Updated'] );
    $template->set ( '@date_upgraded', $lang['Date_Upgraded'] );

    $template->set ( '@hits', $lang['Hits'] );
    
    $template->set ( '@view_realtor', $lang['View_Realtor'] );

    $template->set ( '@image_url', URL . '/templates/' . $cookie_template . '/images' );

    //

    // Set background color
    $bgcolor = ''; // Background color for all odd listings
    $bgcolor2 = $conf['list_background_color_even']; // Background color for all even listings
    
    if ( $i%2 == 0 )
     $template->set ( 'bgcolor', $bgcolor );
    else
     $template->set ( 'bgcolor', $bgcolor2 );

    // Publish template
    $template->publish();
    
    $i++;

   // Show banner ad in the middle of the search results
   if ($i == ceil($db->numrows( $r2 )/2))
    echo implode ('', file( PATH . '/templates/' . $cookie_template . '/tpl/property_search_short_ad.tpl' ));

   }

  echo '
   </table>';

  // Pagination

  // Generate GET vars and push it into the session variable
  // to be able to return to this search page later
//  $session->varunset('listingsearchvariablespage');
//  $searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode($value) . '&amp;';
//  $session->set('listingsearchvariablespage', $searchURL);

  echo '<br />';

  $results = $db->numrows( $r );

  // If number of results is bigger than the maximum number
  // of search results set in config we start the pagination
  if ( $results > $conf['search_results'] )

   {

    // Calculate the first number of page to show
    // This makes the list of pages numbers smaller
    if ((($page*$conf['search_results'])-($conf['search_results']*5)) >= 0) 
     $first=($page*$conf['search_results'])-($conf['search_results']*5);
    else 
     $first=0;

    // Calculate the last element of the pagination list
    if ((($page*$conf['search_results'])+($conf['search_results']*6)) <= $results) 
     $last =($page*$conf['search_results'])+($conf['search_results']*6);
    else 
     $last = $results;

    @    $i=$first/$conf['search_results'];

    // Previous link
    if ($page > 0)
     {
      $pagenum = $page - 1;
      echo ' <a href="' . URL . '/search.php?page=' . $pagenum . '&amp;' . $session->fetch('listingsearchvariablespage') . '">' . $lang['Previous'] . '</a> | ';
     }

    // Middle pagination
    for ( $step = $first; $step < $last; $step=$step+$conf['search_results'] )

     {

      if ( $i == $page )

       {

	$pagenum = $i+1;
	echo ' <span class="warning">' . $pagenum . '</span> | ';
	$i++;

       }

      else

       {

	$pagenum = $i+1;
	echo ' <a href="' . URL . '/search.php?page=' . $i . '&amp;' . $session->fetch('listingsearchvariablespage') . '">' . $pagenum . '</a> | ';
	$i++;

       }

     }

    // Next link
    if ($page - (($results / $conf['search_results']) - 1) < 0)
     {
      $pagenum = $page+1;
      echo ' <a href="' . URL . '/search.php?page=' . $pagenum . '&amp;' . $session->fetch('listingsearchvariablespage') . '">' . $lang['Next'] . '</a>';      
     }

   }

  if ($db->numrows($r) != 0)
   echo '<input type="Submit" value="' . $lang['Compare_Listings'] . '" class="submit"></form>';

  // Pagination : END
  echo table_footer ();

 }

 $r2 = $db->query($sql2);

 if ($db->numrows($r2) > 0)
  {
  
	echo table_header ( $lang['View_Map'] );
	
	echo '<div align="center">';
	
	//customization options are here
	$map->zoomLevel = $conf['map_zoom'];             //zoom out as far as we can
	$map->setWidth($conf['map_width']);            //pixels
	$map->setHeight($conf['map_height']);           //pixels
	$map->controlType = 'large';    //show large controls on the side
	$map->showType = false;         //hide the map | sat | hybrid buttons
	
	while ($f = $db->fetcharray( $r2 ))
	{
	
	 if ($conf['rewrite'] == 'ON')
	  $link = '<a href=' . URL . '/Listing/' . rewrite(getnamebyid(TYPES_TABLE, $f['type'])) . '/' . $f['id'] . '_' . rewrite($f['title']) . '.html><strong>' . $f['title'] . '</strong></a> <br />' . $f['address1'] . ' ' . $f['address2'] . '<br />' . $f['zip'];
	 else
	  $link = '<a href=' . URL . '/viewlisting.php?id=' . $f['id'] . '><strong>' . $f['title'] . '</strong></a> <br />' . $f['address1'] . ' ' . $f['address2'] . '<br />' . $f['zip'];
	
	 $cat = explode ("#", $f['location2']);
	 $r11 = $db->query('SELECT category FROM ' . LOCATION1_TABLE . ' WHERE selector = "' . $cat[0] . '"');
	 $f11 = $db->fetcharray($r11);
	
	 $r22 = $db->query('SELECT subcategory FROM ' . LOCATION2_TABLE . ' WHERE catsubsel = "' . $cat[1] . '"');
	 $f22 = $db->fetcharray($r22);
	
	 $r33 = $db->query('SELECT subsubcategory FROM ' . LOCATION3_TABLE . ' WHERE catsubsubsel = "' . $cat[2] . '"');
	 $f33 = $db->fetcharray($r33);
	
	 if (empty($f['latitude']) || empty($f['longitude'])) {
	  $latlng = $map->addAddress($f['address1'] . ' ' . $f['address2'] . ' ' . $f33['subsubcategory'] . ' ' . $f22['subcategory'] . ' ' . $f11['category'] . ' ' . $f['zip'], $link);
       if ($latlng !== null) {
           list($f['latitude'], $f['longitude']) = explode(',', $latlng);
           $sql = 'UPDATE '.PROPERTIES_TABLE.' 
                   SET latitude = "'.floatval($f['latitude']).'", 
                       longitude = "'.floatval($f['longitude']).'" 
                   WHERE id = '.$f['id'];
           $r_maps = $db->query($sql) or error('Critical Error', mysql_error());
           $db->freeresult($r_maps);
       }
	  } else
	  $map->addGeoPoint( $f['latitude'], $f['longitude'], $link);
	
	}
	
	$map->showMap();
	
	echo '</div>';
	
	echo table_footer ();
	
  }

// Template footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>